//
//  MainTabBar.swift
//  SinaWeibo
//
//  Created by 林柱强 on 16/1/28.
//  Copyright © 2016年 林柱强. All rights reserved.
//

import UIKit

class MainTabBar: UITabBar {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    //如果重写 init(frame: CGRect) 系统会认为这个空间是通过代码创建的
    required init?(coder aDecoder: NSCoder) {
        
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        //手动修改所有按钮的位置
        let width = bounds.width / 5
        let height = bounds.height
        let rect = CGRect(x: 0, y: 0, width: width, height: height)
        
        //定义递增变量
        var index: CGFloat = 0
        for subview in subviews {
            if subview.isKindOfClass(NSClassFromString("UITabBarButton")!){
                //修改frame
                subview.frame = CGRectOffset(rect,index * width, 0)

                index += index == 1 ? 2 : 1
            }
        }
        
        //设置攥写按钮位置
        composeBtn.frame = CGRectOffset(rect, width * 2, 0)
        bringSubviewToFront(composeBtn)
    }

    private func setupUI() {
        //添加攥写按钮
        addSubview(composeBtn)
    }
    
    //MARK： 懒加载 攥写按钮
    lazy var composeBtn: UIButton = {
        //UIButton() 自定义样式的按钮
        let btn = UIButton()
        
        //设置按钮背景颜色
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
        //设置按钮颜色
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
        btn.sizeToFit()//与背景色大小一样
        
        return btn
    }()
    
}
